
import { map, filter, catchError, tap } from 'rxjs/operators';
import {HttpClient, HttpHeaders, HttpRequest, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';

import {serialize} from '../../../utils/serialize';


export enum RequestMethod {
    Get = 'GET',
    Head = 'HEAD',
    Post = 'POST',
    Put = 'PUT',
    Delete = 'DELETE',
    Options = 'OPTIONS',
    Patch = 'PATCH'
}

@Injectable()
export class HttpService {
    private _loading = false;
    headers = new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        'ngsw-bypass': 'true'
    });
    /** 是否正在加载中 */
    get loading(): boolean {
      return this._loading;
    }
    begin() {
      // console.time('http');
      setTimeout(() => (this._loading = true));
    }

    end() {
      // console.timeEnd('http');
      setTimeout(() => (this._loading = false));
    }
    constructor(private http: HttpClient) {
    }

    get(url: string, args?: any, customHeaders?: HttpHeaders): Observable<any> {
        const options = {
            headers: customHeaders || this.headers,
            withCredentials: true
        };
        if (args) {
            options['params'] = serialize(args);
        }
        return this.http.get(url, options).pipe(catchError(this.checkError.bind(this)));
    }

    post(url: string, body: any, customHeaders?: HttpHeaders, responseType?: any): Observable<any> {
        return this.request(url, body, RequestMethod.Post, customHeaders, responseType);
    }

    put(path: string, body: any): Observable<any> {
        return this.request(path, body, RequestMethod.Put);
    }

    delete(url: string, body?: any): Observable<any> {
        return this.request(url, body, RequestMethod.Delete);
    }

    private request(url: string, body: any, method: string, customHeaders?: HttpHeaders, responseType?: any): Observable<any> {
        const req = new HttpRequest(method, url, body, {
            headers: customHeaders || this.headers,
            responseType: responseType || 'json',
            withCredentials: true
        });
        this.begin();
        return this.http.request(req).pipe(
            tap(() => {
              this.end();
            }),
            filter(response => response instanceof HttpResponse),
            map((response: HttpResponse<any>) => {
                    return response.body;
                }
            ),
            catchError(error => this.checkError(error)), );
    }

    // 服务器错误
    private checkError(error: any): any {
        if (error && error.status === 401) {
            console.log('401---------------------');
        } else {
            console.log(error);
        }
        throw error;
    }
}

